package com.shu.qq.utils

import android.content.Context
import android.content.SharedPreferences
import java.lang.ClassCastException


class SharedPreferenceHelper constructor(
    private val context: Context,
    private val fileName: String
) {
    private val sharedPreferences: SharedPreferences =
        context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
    private val editor: SharedPreferences.Editor = sharedPreferences.edit();

    /**
     * 添加值
     */
    fun put(key: String, value: Any) {
        when (value) {
            is String -> {
                editor.putString(key, value);
            }
            is Int -> {
                editor.putInt(key, value)
            }
            is Boolean -> {
                editor.putBoolean(key, value)
            }
            is Float -> {
                editor.putFloat(key, value)
            }
            is Long -> {
                editor.putLong(key, value)
            }
            else -> {
                return
            }
        }
        editor.commit();
    }

    /**
     * 获取值
     */
    fun get(key: String, value: Any): Any? {
        when (value) {
            is String -> {
                return sharedPreferences.getString(key, value)
            }
            is Int -> {
                return sharedPreferences.getInt(key, value)
            }
            is Boolean -> {
                return sharedPreferences.getBoolean(key, value)
            }
            is Float -> {
                return sharedPreferences.getFloat(key, value)
            }
            is Long -> {
                return sharedPreferences.getLong(key, value)
            }
            else -> {
                throw ClassCastException("请求类型不存在")
            }

        }
    }

    fun putStringSet(key: String, value: Set<String>) {
        editor.putStringSet(key, value)
        editor.commit()
    }

    fun getStringSet(key: String): Set<String>? {
        return sharedPreferences.getStringSet(key, null);
    }

    /**
     * 获取所有值
     */
    fun getAll(): Map<String, *>{
        return sharedPreferences.all
    }

    /**
     * 删除值
     */
    fun remove(key: String){
        editor.remove(key)
        editor.commit()
    }

    /**
     * 清除所有值
     */
    fun clear(){
        editor.clear()
        editor.commit()
    }

    /**
     * 检查该值是否存在
     */
    fun contain(key: String): Boolean{
        return sharedPreferences.contains(key)
    }
}